package com.wanxi.util;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

/**
 * Created by IntelliJ IDEA.
 * 统计controller内的方法运行一次需要多长时间
 * @Author : 林子淳
 * @create 2023/3/14 13:31
 */
public class ProcedureWorkpieceRatio implements HandlerInterceptor {
    private Jedis jedis = new Jedis();
    long stime;
    long etime;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在拦截点执行前拦截，如果返回true则不执行拦截点后的操作（拦截成功）
        //开始时间
        if (handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod) handler;
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            stime =System.currentTimeMillis();
            System.out.println("用户想执行的操作是:" + h.getMethod().getName() + "开始时间" + df.format(stime));

        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod) handler;
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            etime = System.currentTimeMillis();
            System.out.println("用户想执行的操作是:" + h.getMethod().getName() + "结束时间" + df.format(etime)+",执行时长："+(etime-stime));
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在处理过程中，执行拦截

    }
}
